* Tariffs tau_it_S - industry level tariffs
* Updated March 3 moxnes@gmail.com

* Dependencies: This file requires running
* firm_patents2.do -> generates patentsfam2.dta
* weights_wic3.do -> Generates weightswic3.dta


cd /users/andreas/dropbox/work/patstat/data
global tmp "/tmp"

* Tariff for home country
use tariffreshape, clear
ren tariff* tauthq*
ren appln headq
save $tmp/tariffreshapeHQ, replace

use $tmp/tmpnace, clear
ren tariff* tauthq*
ren appln headq
save $tmp/tmpnaceHQ, replace

* ----------------------------------------------
* Restrict sample to firms with at least 1 patent in the post period
* ----------------------------------------------
use patentsfam3, clear
keep if y>=1992
keep if headq~=""
contract hrm
keep hrm
save $tmp/sample, replace

* ----------------------------------------------
* Merge tafiff data and weight wic
* ----------------------------------------------
use weightswic5_to1985, clear 				// Baseline
*use weightswic5_to1975, clear  			// Placebo
*use weightswic5_to1985_predicted, clear 	// Predicted weights

capture drop p tot
drop if headq==""

/* * Merge tariff for destination country
*replace nace=99 if nace==.  // Use these obs??
merge m:1 appln nace2_1 using tariffreshape, keep(match master)
drop _merge

* Mark missing tariffs and set them to zero for every year
count
gen MissTar = tariff1992==.
foreach vv of varlist tariff???? {
  replace `vv' = 0 if `vv'==.
}
*/

* Merge RTA variable
merge m:1 headq appln using rta, keep(match master)
drop _merge

* If missing RTA, set it to zero
gen Missrta = rta1992==.
foreach vv of varlist rta???? {
  replace `vv' = 0 if `vv'==.
}

* Merge tariff for home country
merge m:1 headq nace2_1 using $tmp/tariffreshapeHQ, keep(match master)

* If missing tariff, set it to zero for every year
gen MissTarhq = tauthq1992==.
foreach vv of varlist tauthq???? {
  replace `vv' = 0 if `vv'==.
}

save $tmp/tmp, replace

use $tmp/tmp, clear
gen homecty = appln_auth==headq 
gen homew = w if homecty==1

* Export weights
gen wEx = w
replace wEx = 0 if homecty==1
egen tmp = sum(wEx), by(hrm)
*replace wEx = wEx/tmp
gen wEx2 = wEx/tmp
drop tmp

*gen Missing = MissTar | MissTarhq | Missrta
*gen Missing = MissTar

* Assume bilateral tariff is zero if RTA
forvalues i=1992/2006 {
  gen tariffApplied`i' =  tauthq`i'*(~rta`i')
}

forvalues i=1992/2009 {
  gen tautImp`i' = tauthq`i'*wEx2 
} 

forvalues i=1992/2006 {
  gen tautAppImp`i' = tariffApplied`i'*wEx2
} 

collapse (sum) tautImp???? tautAppImp???? Miss*, by(hrm headq nace)

save tauT5d_Imp, replace

